package com.soft.javase.day14.groupchat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author yzg
 * @desc TODO
 * @date 2025/5/24
 */
public class GroupChatServer {
    private static final Map<Socket, PrintWriter> socketMap = new HashMap<>();

    public static void main(String[] args) {
        ExecutorService pool = Executors.newCachedThreadPool();
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("聊天服务器已启动，等待客户端接入...");
            while (true) {
                Socket socket = serverSocket.accept();
                PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
                socketMap.put(socket, pw);
                System.out.println("新客户端连接: " + socket.getRemoteSocketAddress());
                pool.execute(() -> socketHandle(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void socketHandle(Socket socket) {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
            String message;
            while ((message = br.readLine()) != null) {
                if (message.equalsIgnoreCase("exit")) {
                    System.out.println("客户端"+socket.getRemoteSocketAddress()+"下线");
                    break;
                }
                broadcast(message, socket);
            }
        } catch (IOException e) {
            System.out.println("客户端"+socket.getRemoteSocketAddress()+"下线");
            socketMap.remove(socket);
        }
    }

    private static void broadcast(String message, Socket es) {
        socketMap.forEach((socket, writer) -> {
            if (socket != es) {
                writer.println(message);
            }
        });
    }
}
